package com.cwx.web;

import com.alibaba.fastjson.JSONObject;
import com.cwx.common.Json;
import com.cwx.dao.entity.Member;
import com.cwx.dao.entity.OrderInfo;
import com.cwx.service.MemberService;
import com.cwx.service.OrderInfoService;
import com.cwx.utils.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by ligang on 2017/9/19.
 */
@RequestMapping("/orderInfo")
@Controller
public class OrderInfoController {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private MemberService memberService;

    @RequestMapping("/apply/{phone}/{key}")
    @ResponseBody
    public Json apply(@RequestBody /*@Valid*/ OrderInfo orderInfo, @PathVariable String phone, @PathVariable String key){
        Json json = new Json();
        Cache cache = cacheManager.getCache("keyCache");
        if (cache.get(phone) == null || cache.get(phone).get().toString() == null || !cache.get(phone).get().toString().equals(key)){
            json.setCode("20018");
            json.setMessage("二维码已失效,请重新扫码申请！");
            return json;
        }
        try {
            Member member = memberService.findByPhone(phone);
            orderInfo.setOrderNo(System.currentTimeMillis() + Tool.randomStrNum(100000,999999));
            orderInfo.setStatus(OrderInfo.PENDING_REVIEW);
            orderInfo.setOrderTime(new Date());
            orderInfo.setMember(member);
            orderInfoService.apply(orderInfo);
            json.setCode("10010");
            json.setMessage("保存成功");
            cache.evict(phone);
        }catch (Exception e){
            json.setCode("20017");
            json.setMessage("保存失败");
        }
        System.out.println(json.getCode());
        return json;
    }
    @RequestMapping("/applyFromWechat")
    @ResponseBody
    public Json applyFromWechat(@RequestBody /*@Valid*/ OrderInfo orderInfo,HttpSession session){
        Json json = new Json();
        Member member = (Member) session.getAttribute("member");
        try {
            orderInfo.setOrderNo(System.currentTimeMillis() + Tool.randomStrNum(100000,999999));
            orderInfo.setStatus(OrderInfo.PENDING_REVIEW);
            orderInfo.setOrderTime(new Date());

            orderInfo.setMember(member);
            orderInfo.setAdvertisement("12345"); // 默认商户号
            orderInfoService.save(orderInfo);
            json.setObj(orderInfo.getId());
            json.setCode("10010");
            json.setMessage("保存成功");
        }catch (Exception e){
            json.setCode("20017");
            json.setMessage("保存失败");
        }
        return json;
    }

    @RequestMapping("/list")
    @ResponseBody
    public Json list(HttpSession session ,int currentPage,int size){
        Json json = new Json();
        try{
            Member member = (Member) session.getAttribute("member");
            PageRequest pr = new PageRequest(currentPage - 1, size, Sort.Direction.DESC, "orderTime");
            List<OrderInfo> orderInfos = orderInfoService.findByMemberId(member.getId(),pr);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("count",orderInfoService.countOrderInfoByMemberId(member.getId()));
            jsonObject.put("orderInfos",orderInfos);
            json.setCode("10011");
            json.setMessage("获取订单列表成功");
            json.setObj(jsonObject);
        }catch (Exception e){
            json.setCode("20018");
            json.setMessage("获取订单列表失败，请稍后重试!");
        }
        return json;
    }

}